﻿using Common.Contract.Warranty.Record;
using Common.Contract.Warranty.Request;
using Common.Contract.Warranty.Response;
using Common.Contract.Paging;
using Common.Service.Command;
using Warranty.Model.Interface;
using Warranty.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Warranty.ServiceCommand
{
    public class SearchResponseSMSServiceCommand : ProviderServiceCommand<IResponseSMSProvider, SearchResponseSMSRequest, SearchResponseSMSResponse>
    {

        public SearchResponseSMSServiceCommand(IResponseSMSProvider providers) : base(providers) { }

        protected override void Validate(SearchResponseSMSRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
        }

        protected override bool OnExecute(SearchResponseSMSResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0, totalPages = 0;
            List<ResponseSMSRecord> records = new List<ResponseSMSRecord>();
            var applicationKey = Request.Header.ApplicationKey;
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }
            List<ResponseSMS> responseSMS = null;
            if (string.IsNullOrWhiteSpace(Request.TextSearch))
            {
                responseSMS = Providers.SearchResponseSMS(out totalRecord, Request.GabitId, Request.RespType, pageSize, pageIndex);
            }
            else
            {
                responseSMS = Providers.SearchResponseSMS(out totalRecord, Request.TextSearch, pageSize, pageIndex);
            }
            if (responseSMS != null)
            {
                records = responseSMS.Select(x => new ResponseSMSRecord
                {
                    CreateDate = x.CreateDate,
                    GabitId = x.GabitId,
                    GabitTemplate = x.GabitTemplate,
                    MsgBodyLen = x.MsgBodyLen,
                    Purpose = x.Purpose,
                    RespMsg1 = x.RespMsg1,
                    RespMsg2 = x.RespMsg2,
                    RespType = x.RespType,
                    Template = x.Template
                }).ToList();
            }
            response.Records = records;
            response.Page = new PageRecord
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecords = totalRecord
            };
            return isSuccess;
        }
    }
}
